package com.solution.wx.shoppingcart.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.solution.admin.area.entity.AreaEntity;
import com.solution.admin.area.service.AreaService;
import com.solution.admin.coupon.constants.CouponConstants;
import com.solution.admin.coupon.entity.CouponEntity;
import com.solution.admin.coupon.service.CouponService;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CompanyExpressConfigEntity;
import com.solution.admin.customer.entity.DeliveryAddressEntity;
import com.solution.admin.customer.entity.DeliveryModeEntity;
import com.solution.admin.customer.service.CompanyExpressConfigService;
import com.solution.admin.customer.service.CompanyService;
import com.solution.admin.customer.service.DeliveryAddressService;
import com.solution.admin.customer.service.DeliveryModeService;
import com.solution.admin.order.constants.OrderConstants;
import com.solution.admin.order.entity.OrderInvoiceEntity;
import com.solution.admin.order.service.OrderInvoiceService;
import com.solution.admin.point.entity.PointEntity;
import com.solution.admin.point.service.PointService;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.entity.ProductImageEntity;
import com.solution.admin.product.entity.ProductPriceEntity;
import com.solution.admin.product.entity.ProductSpecEntity;
import com.solution.admin.product.entity.ProductSpecRelaEntity;
import com.solution.admin.product.service.ProductImageService;
import com.solution.admin.product.service.ProductService;
import com.solution.admin.product.service.ProductSpecService;
import com.solution.admin.promotion.entity.PromotionProductEntity;
import com.solution.admin.promotion.service.PromotionProductService;
import com.solution.admin.promotion.service.PromotionService;
import com.solution.admin.promotion.service.PromotionTargetService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.promotion.PromotionCheckUtil;
import com.solution.pc.shoppingcart.entity.ShoppingCartEntity;
import com.solution.pc.shoppingcart.service.ShoppingCartService;
import com.solution.wx.common.constants.PublicConstants;

/**
 * 微信购物车web控制层
 * @author lilp
 * @date 2017-10-13 20:05:27
 */
@RequestMapping("/wx/shoppingcart")
@Controller("wxShoppingCartController")
public class ShoppingCartController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(ShoppingCartController.class);

	@Autowired
	private ShoppingCartService shoppingCartService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private ProductImageService productImageService;
	
	@Autowired
	private DeliveryAddressService deliveryAddressService;
	
	@Autowired
	private ProductSpecService productSpecService;
	
	@Autowired
	private PromotionProductService promotionProductService;
	
	@Autowired
	private PromotionTargetService promotionTargetService;
	
	@Autowired
	private PromotionService promotionService;
	
	@Autowired
	private AreaService areaService;
	
	@Autowired
	private DeliveryModeService deliveryModelservice;
	
	@Autowired
	private PointService pointService;
	
	@Autowired
	private PromotionCheckUtil promotionCheckUtil;
	
	@Autowired
	private CouponService couponService;
	
	@Autowired
	private OrderInvoiceService orderInvoiceService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private CompanyExpressConfigService companyExpressConfigService;
	
	/**
	 * 查询购物车商品
	 * @param ShoppingCart 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-10-13 20:05:27
	 */
	@RequestMapping("/list")
	public String toListShoppingCartPage(ShoppingCartEntity shoppingCart, HttpServletRequest request) {
		request.setAttribute(PublicConstants.CURRENT_PAGE_KEY, PublicConstants.PAGE_SHOPPING_CART);
		
		Map<String, Object> param = new HashMap<String, Object>();
		// 检查用户已经登录、并且购物车中有session_id 关联的商品，转移到登录用户名下
		if(isLogin(request)){
			String sessionId = request.getSession().getId();
			// 匿名登录时，使用sessionId 后20位添加购物车商品
			param.put("userCode", sessionId.substring(12));
			param.put("loginUserCode", getUserCode());
			shoppingCartService.transferShoopingcartProduct(param);
		}
		
		// 查询目前购物车中的商品
		/**
		 * 考虑：未登录用户的购物车怎么处理:
		 * sessionId作为当前用户的Id,保存购物车商品，如果登录后，将购物车移到用户名下
		 */
		String userCode = getCurrentUserCodeWithAnonymous(request);
		param.put("userCode", userCode);
		List<ShoppingCartEntity>  cartList = shoppingCartService.listShoppingCart(param);
		
		//购物车中商品ID集合
		List<String> productIdList = new ArrayList<String>();
		//远购物车中的商品基价
		Map<String, Object> oldProductPriceMap = new HashMap<String, Object>();
		// 用于根据商品编码product_code批量查询是否有参加活动
		List<String> productCodeList = new ArrayList<String>();
		
		if(cartList != null && cartList.size() > 0){
			for (ShoppingCartEntity product : cartList) {
				productIdList.add(String.valueOf(product.getProductId()));
				oldProductPriceMap.put(String.valueOf(product.getProductId()), product.getProductPrice());
				// 解析商品规格项
				if(StringUtil.isNotEmpty(product.getProductSpec())){
					List<ProductSpecEntity> productSpecList = JSONArray.parseArray(product.getProductSpec(), ProductSpecEntity.class);;
					product.setSpecList(productSpecList);
				}
				productCodeList.add(product.getProductCode());
			}
		}
		
		//查询商品的最新价格,防止加入购物车商品的价格发生变动 
		//查询商品的最新价格,防止加入购物车商品的价格发生变动 
		if (cartList != null && cartList.size() > 0) {
			Map<String, Object> productPriceParamMap = new HashMap<String, Object>();
			productPriceParamMap.put("isLogin", isLogin(request) ? "1" : "0");
			productPriceParamMap.put("customerLevel", getCustomerLevel());
			productPriceParamMap.put("ids", productIdList);
			// 根据商品ID和商品ID批量获取商品基价
			List<ProductEntity> productPriceList = productService.listProductBasePrice(productPriceParamMap);
			Map<Long, ProductEntity> tmpBaseProdutMap = new HashMap<Long, ProductEntity>();
			if (productPriceList != null && productPriceList.size() > 0) {
				for (ProductEntity productEntity : productPriceList) {
					tmpBaseProdutMap.put(productEntity.getId(), productEntity);
				}
			}

			for (ShoppingCartEntity cartItem : cartList) {
				ProductEntity tmpProduct = tmpBaseProdutMap.get(cartItem.getProductId());
				// 主商品价格 = 基价 + 客户差价
				BigDecimal productPrice = tmpProduct.getProductPrice();
				// 商品规格的价格
				BigDecimal specPrice = new BigDecimal(0);
				// 最终商品价格 = 基价+级别差价+默认规格价格
				BigDecimal finalProductPrice = new BigDecimal(0);

				// 获取购物车中该商品的规格
				List<ProductSpecEntity> productSpecList = cartItem.getSpecList();

				// 获取商品规格的价格
				Map<String, Object> specParam = new HashMap<String, Object>();
				specParam.put("productId", tmpProduct.getId());
				// 查询商品所有规格价格
				List<ProductSpecRelaEntity> productSpecRelaList = productService
						.listProductSpecPriceByProductId(specParam);
				// 循环购物中商品的规格
				if (productSpecList != null && productSpecList.size() > 0) {
					if (StringUtil.isNotEmpty(productSpecRelaList.get(0).getProductSpecListStr())) {
						List<ProductSpecRelaEntity> tmpSpecList = JSONArray.parseArray("["+ productSpecRelaList.get(0).getProductSpecListStr() + "]",
										ProductSpecRelaEntity.class);
						for (ProductSpecRelaEntity tempProductSpecRela : tmpSpecList) {
							for (ProductSpecEntity ps : productSpecList) {
								if (ps.getId().equals(tempProductSpecRela.getId())) {
									specPrice = specPrice.add(tempProductSpecRela.getSpecPrice());
								}
							}
						}
					}
				}

				// 计算最终价格
				finalProductPrice = productPrice.add(specPrice);
				if (!finalProductPrice.equals(cartItem.getProductPrice())) {
					// 修改数据库的购物车表中的价格
					ShoppingCartEntity shoppingCartParam = new ShoppingCartEntity();
					shoppingCartParam.setId(cartItem.getId());
					shoppingCartParam.setBuyNum(cartItem.getBuyNum());
					shoppingCartParam.setProductBasePrice(tmpProduct.getBasePrice());
					shoppingCartParam.setProductPrice(finalProductPrice);
					shoppingCartService.updateShoppingCart(shoppingCartParam);
				}
			}
		}
		
		BigDecimal totalPrice = new BigDecimal(0);
		if(cartList != null && cartList.size() > 0){
			for (ShoppingCartEntity product : cartList) {
				// 计算购物车小计、总价
				product.setSubTotalProductPrice(product.getProductPrice().multiply(new BigDecimal(product.getBuyNum())));
				totalPrice = totalPrice.add(product.getSubTotalProductPrice());
			}
		}
		
		
		// 查询商品活动活动，微信端的购物车需要计算出，活动(满减、满折、满赠)后的订单价格；不同于优惠券，优惠券的使用在结算时使用
		promotionCheckUtil.checkPromotion(cartList, productCodeList, getCustomerId());
		
		// 提取购物车活动的满减和折扣，体现到最终的购物车结算价格上面
		BigDecimal reduceMoney = new BigDecimal(0);
		BigDecimal discountMoney = new BigDecimal(0);
		for (ShoppingCartEntity cartItem : cartList) {
			List<PromotionProductEntity> reduceList = cartItem.getReduceList();
			if(reduceList != null && reduceList.size() > 0){
				for (PromotionProductEntity reduce : reduceList) {
					reduceMoney = reduceMoney.add(reduce.getReduceMoney());
				}
			}
			
			List<PromotionProductEntity> discountList = cartItem.getDiscountList();
			if(discountList != null && discountList.size() > 0){
				for (PromotionProductEntity discount : discountList) {
					// 如： 打9折，  折扣金额  = (10 - 9[折扣])*商品购物小计
					discountMoney = discountMoney.add((new BigDecimal(10).subtract(discount.getDiscount())).multiply(cartItem.getSubTotalProductPrice()));
				}
			}
		}
		// 购物车总价格 = 商品价格 - 满减活动金额  - 满折活动折扣金额 
		totalPrice = totalPrice.subtract(reduceMoney).subtract(discountMoney);
		// 购物车总价格
		request.setAttribute("totalPrice", totalPrice);
		// 购物车商品列表
		request.setAttribute("shoppingcart", cartList);
		return "wx/shoppingcart/shoppingcart";
	}
	 
	
	
	/**
	 * 编辑购物车数量
	 * @param shoppingCart 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-10-13 20:05:27
	 */
	@RequestMapping("/editBuyNum")
	@ResponseBody
	public Map<String, Object> editBuyNum(ShoppingCartEntity shoppingCartEntity, HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 添加购物车
			int result = shoppingCartService.updateShoppingCart(shoppingCartEntity);
			if(result != 0){
				resultMap.put(PublicStatus.RESULT_CODE, "1");
				resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
			}else{
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			}
		} catch (Exception e) {
			handleException("往购物车中添加商品失败", logger, e);
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
		}
		return  resultMap;
	}
	
	/**
	 * 添加商品，并立马跳转到购物车页面 (不同于一键下单，跳转到支付页面的功能)
	 * 如果在在分享页面单击的立即购买，则带上分享id跳转结算页面，提交订单保存
	 * @param shoppingCart 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-10-13 20:05:27
	 */
	@RequestMapping("/directAdd")
	public String addAndToShoppingCart(ShoppingCartEntity shoppingCartEntity, HttpServletRequest request){
		long id = 0;
		String redirectUrl = "redirect:/wx/shoppingcart/settlement?shoppingIds=";
		try {
			// 添加购物车
			id = saveOrUpdateShoppingCart(shoppingCartEntity, request);
			redirectUrl += id;
			//如果是分享页面下单则需要记录该订单
			String shareId = request.getParameter("shareId");
			if (StringUtil.isNotNull(shareId)) {
				redirectUrl = redirectUrl + "&shareId=" + shareId;
			}
		} catch (Exception e) {
			handleException("往购物车中添加商品失败", logger, e);
		}
		// return  "redirect:/wx/shoppingcart/list";
		return  redirectUrl;
	}
	
	/**
	 * 删除购物车商品
	 * @param shoppingCartEntity
	 * @param request
	 * @return
	 */
	@RequestMapping("/deleteCartItem")
	public String deleteCartItem(ShoppingCartEntity shoppingCartEntity, HttpServletRequest request){
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			List<String> sids = new ArrayList<String>();
			String ids = request.getParameter("ids");
			if(StringUtil.isNotEmpty(ids)){
				for (String id : ids.split(",")) {
					sids.add(id);
				}
			}
			param.put("ids", sids);
			shoppingCartService.deleteShoppingCartProduct(param);
		} catch (Exception e) {
			handleException("删除购物车商品失败", logger, e);
		}
		return  "redirect:/wx/shoppingcart/list";
	}
	
	

	/**
	 * 往购物车中添加商品失败
	 * @param shoppingCart 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-10-13 20:05:27
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> addProductToShoppingCart(ShoppingCartEntity shoppingCartEntity, HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 添加购物车
			long id = saveOrUpdateShoppingCart(shoppingCartEntity, request);
			if(id != 0){
				resultMap.put(PublicStatus.RESULT_CODE, "1");
				resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
			}else{
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			}
			return resultMap;
		} catch (Exception e) {
			handleException("往购物车中添加商品失败", logger, e);
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
		}
		return resultMap;
	}
	
	
	/**
	 * 添加或修改购物车
	 * @param shoppingCartEntity
	 * @param request
	 * @return
	 */
	private long saveOrUpdateShoppingCart(ShoppingCartEntity shoppingCartEntity , HttpServletRequest request){
		
		// 商品规格
		String specList = request.getParameter("specListJson");
		List<ProductSpecEntity> productSpecList = null;
		if(!"[]".equals(specList)){
			productSpecList = JSONArray.parseArray(specList, ProductSpecEntity.class);
		}
		
		/**
		StringBuffer specNameBuf = new StringBuffer("【");
		if(productSpecList != null && productSpecList.size() > 0){
			for (ProductSpecEntity spec : productSpecList) {
				if(productSpecList.indexOf(spec) != productSpecList.size()-1){
					specNameBuf.append(spec.getSpecName()).append("：").append(spec.getSpecValue()).append(",");
				}else{
					specNameBuf.append(spec.getSpecName()).append("：").append(spec.getSpecValue());
				}
			}
			specNameBuf.append("】");
		}
		if("【".equals(specNameBuf.toString())){
			specNameBuf = new StringBuffer();
		}
		*/
		
		// 查询商品信息
		long productId = shoppingCartEntity.getProductId();
		ProductEntity product = productService.getProductById(productId);
		// 查询商品价格【为安全， 凡是涉及商品金额的，要后台重新计算，不采用前台传入的价格】
		BigDecimal productPrice = product.getBasePrice();
		// 模拟成本
		BigDecimal simuliationPrice = product.getSimulationPrice();
		List<ProductPriceEntity> priceList = productService.getProductPriceList(productId);
		// 客户级别  订单货价 = 基本价 - 客户级别差价
		String customerLevel = getCustomerLevel();
		if (priceList != null && priceList.size() > 0) {
			for (ProductPriceEntity price : priceList) {
				if (customerLevel.equals(price.getPriceLevel())) {
					productPrice = productPrice.add(price.getDiffPrice());
					simuliationPrice = simuliationPrice.add(price.getDiffPrice());
					break;
				}
			}
		}
		
		// 查询商品规格项的价格
		if(productSpecList != null && productSpecList.size() > 0){
			for (ProductSpecEntity productSpec : productSpecList) {
				// 查询规格价格
				ProductSpecEntity ppe = productSpecService.getProductSpecById(productSpec.getId());
				// 添加规格项的价格加到商品价格上
				productPrice = productPrice.add(ppe.getSpecPrice());
				simuliationPrice = simuliationPrice.add(ppe.getSpecPrice());
			}
		}
		
		// 设置商品价格
		shoppingCartEntity.setProductPrice(productPrice);
		
		// 设置商品主图片
		List<ProductImageEntity> productImageList = productImageService.listProductImageForProductDetail(productId);
		if (productImageList != null && productImageList.size() > 0) {
			for (ProductImageEntity productImage : productImageList) {
				if (1 == productImage.getImageType()) {
					// 主图
					shoppingCartEntity.setImagePath(productImage.getImagePath());
					break;
				}
			}
		}

		// 货主设置
		// TODO
		shoppingCartEntity.setProductOwnerCode(1);
		// 商品名称
		shoppingCartEntity.setProductName(product.getProductName());
		// 商品规格
		shoppingCartEntity.setProductSpec(specList);
		// 设置商品编码
		shoppingCartEntity.setProductCode(product.getProductCode());
		// 设置购物车中的用户名，未登录用户使用sessionId 后20位当作用户名
		String userCode = getCurrentUserCodeWithAnonymous(request);
		shoppingCartEntity.setUserCode(userCode);
		shoppingCartEntity.setCreater(userCode);
		shoppingCartEntity.setProductBasePrice(product.getBasePrice());
		
		// 商品赠送积分
		shoppingCartEntity.setProductPointRatio(product.getPointCieffucuebt());
		// 商品最大可兑换积分
		shoppingCartEntity.setExchangePointRatio(product.getPointExchangeRate());
		// 商品的模拟成本 
		shoppingCartEntity.setProductSimulatePrice(simuliationPrice);
		
		// 添加购物车
		long id = shoppingCartService.saveShoppingCart(shoppingCartEntity);
		return id;
	}
	

	
	/**
	 * 批量删除购物车商品
	 * @param shoppingCart 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-10-13 20:05:27
	 */
	@RequestMapping("/delete")
	public Map<String, Object> deleteShoppingCartProduct(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String userCode = getUserCode();
		String productIds = request.getParameter("productIds");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("userCode", userCode);
		param.put("productIds", productIds);
		try {
			int id = shoppingCartService.deleteShoppingCartProduct(param);
			if(id != 0){
				resultMap.put(PublicStatus.RESULT_CODE, "1");
				resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
			}else{
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			}
			return resultMap;
		} catch (Exception e) {
			handleException("批量删除购物车商品", logger, e);
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
		}
		return resultMap;
	}
	
	/**
	 * 购物车结算
	 * @param ShoppingCart 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-10-13 20:05:27
	 */
	@RequestMapping("/settlement")
	public String settlement(ShoppingCartEntity shoppingCart, HttpServletRequest request) {
		
		// 用于根据商品编码product_code批量查询是否有参加活动
		List<String> productCodeList = new ArrayList<String>();
		
		// 查询目前购物车中的商品
		String userCode = getCurrentUserCodeWithAnonymous(request);
		// 用户勾选要结算的商品
		String shoppingcartIds = request.getParameter("shoppingIds");
		List<String> shoppingcartIdsList = new ArrayList<String>();
		if(StringUtil.isNotEmpty(shoppingcartIds)){
			for (String id : shoppingcartIds.split(",")) {
				shoppingcartIdsList.add(id);
			}
		}
		
		// 查询待结算的商品
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("userCode", userCode);
		param.put("shoppingcartIds", shoppingcartIdsList);
		List<ShoppingCartEntity>  cartList = shoppingCartService.listShoppingCart(param);
		// 商品总金额
		BigDecimal totalProductPrice = new BigDecimal(0);
		// 最大可兑换积分数
		BigDecimal maxUsablePoint = new BigDecimal(0);
		if(cartList != null && cartList.size() > 0){
			for (ShoppingCartEntity product : cartList) {
				// 小计
				product.setSubTotalProductPrice(product.getProductPrice().multiply(new BigDecimal(product.getBuyNum())));
				// 最大可使用积分 = 商品积分最大可兑换比例 * 商品金额 
				maxUsablePoint = maxUsablePoint.add(product.getExchangePointRatio().divide(new BigDecimal(100)).multiply(product.getSubTotalProductPrice()));
				// 订单商品总价格
				totalProductPrice = totalProductPrice.add(product.getSubTotalProductPrice());
				// 格式化商品规格项
				// 解析商品规格项
				if(StringUtil.isNotEmpty(product.getProductSpec())){
					List<ProductSpecEntity> productSpecList = JSONArray.parseArray(product.getProductSpec(), ProductSpecEntity.class);;
					product.setSpecList(productSpecList);
				}
				// 提取商品product_code 字段
				productCodeList.add(product.getProductCode());
			}
		}
		
		// 检查商品是否参加了活动
		promotionCheckUtil.checkPromotion(cartList, productCodeList, getCustomerId());
		
		// 查询收货人地址列表
		String addressId = request.getParameter("addressId");
		if(StringUtil.isNotEmpty(addressId)){
			DeliveryAddressEntity address = deliveryAddressService.getDeliveryAddressById(Long.parseLong(addressId));
			request.setAttribute("address", address);
		}else{
			param.clear();
			param.put("customerId", getCustomerId());
			List<DeliveryAddressEntity> addressList = deliveryAddressService.listDeliveryAddress(param);
			request.setAttribute("addressList", addressList);
			if(addressList != null && addressList.size() > 0){
				request.setAttribute("address", addressList.get(0));
				for (DeliveryAddressEntity address : addressList) {
					if(address.getIsDefault() != null && address.getIsDefault() == 1){
						request.setAttribute("address", address);
					}
				}
			}
		}
		
		// 满减 满折活动金额
		BigDecimal promotionMoney = new BigDecimal(0);
		if(cartList != null && cartList.size() > 0){
			for (ShoppingCartEntity item : cartList) {
				List<PromotionProductEntity>  reduceList = item.getReduceList();
				if(reduceList != null && reduceList.size() > 0){
					for (PromotionProductEntity reduce : reduceList) {
						promotionMoney = promotionMoney.add(reduce.getReduceMoney());
					}
				}
				List<PromotionProductEntity> discountList = item.getDiscountList();
				if(discountList != null && discountList.size() > 0){
					for (PromotionProductEntity discount : discountList) {
						// 折扣优惠金额 =  总商品金额 * （1 - 折扣）/ 10
						promotionMoney = promotionMoney.add(item.getSubTotalProductPrice().multiply(new BigDecimal(10).subtract(discount.getDiscount())).divide(new BigDecimal(10)));
					}
				}
			}
		}
		request.setAttribute("promotionMoney", promotionMoney);
		// 商品总价 - 活动优惠
		BigDecimal realPayMoney = totalProductPrice.subtract(promotionMoney);
		request.setAttribute("realPayMoney", realPayMoney);
		
		// 查询省份列表 
		param.clear();
		param.put("parentId", "1");
		List<AreaEntity> provinceList = areaService.listArea(param);
		request.setAttribute("provinceList", provinceList);
		
		// 支付模式
		String payModel = getCustomerPayModel();
		request.setAttribute("payModel", payModel);
		
		// 配送方式
		
		param.clear();
		param.put("companyId", getCompanyId());
		List<DeliveryModeEntity> deliveryModeList = deliveryModelservice.listDeliveryMode(param);
		request.setAttribute("deliveryModelList", deliveryModeList);
		
		// 查询客户积分及订单最大可使用积分
		param.clear();
		param.put("customerId", getCustomerId());
		List<PointEntity> pointList = pointService.listPoint(param);
		if(pointList != null && pointList.size() > 0){
			// 客户积分余额
			BigDecimal point = pointList.get(0).getPoint();
			// 积分 金额兑换比例,1积分 = 1块钱 
			BigDecimal pointToMoneyExchangeRatio = OrderConstants.POINT_TO_MONEY_EXCHANGE_RATIO;
			// 该笔订单最大可使用积分
			BigDecimal customerPointUsable = maxUsablePoint.multiply(pointToMoneyExchangeRatio);
			request.setAttribute("customerPoint", point);
			// 可使用积分只是10的整数倍,防止出现小数
			if(point.compareTo(customerPointUsable) > 0){
				request.setAttribute("customerPointUsable", (customerPointUsable.intValue()/10)*10);
			}else{
				request.setAttribute("customerPointUsable", (point.intValue()/10)*10);
			}
		}
		
		// 查询用户目前的优惠券
		// 未使用的优惠券
		param.put("isUsed", CouponConstants.IsUsed.UN_USED);
		// 订单商品金额 
		param.put("orderMoney", totalProductPrice);
		List<CouponEntity> couponList = couponService.listUserCoupon(param);
		request.setAttribute("couponList", couponList);
		
		//获取客户最新的开票信息
		OrderInvoiceEntity orderInvoiceInfo = orderInvoiceService.getLatestByCustomerId(getCustomerId());
		request.setAttribute("orderInvoiceInfo", orderInvoiceInfo);
		
		//获取发票增值税发票信息
		CompanyEntity companyInfo = companyService.getCompanyById(this.getCompanyId());
		request.setAttribute("companyInfo", companyInfo);
		
		// 订单商品总价
		request.setAttribute("totalProductPrice", totalProductPrice);
		// 购物车结算商品
		request.setAttribute("shoppingcart", cartList);
		
		
		// 查询结算商品的默认运费，sql直接计算出整个订单商品的默认普通运费多少 ，快递物流运费多少，其它运费多少
		param.clear();
		param.put("shoppingcartIdsList", shoppingcartIdsList);
		ProductEntity deliveryFee = productService.listShoppingcartProductDelivery(param);
		request.setAttribute("deliveryFee", deliveryFee);

		// 获取公司减免地址信息
		param.clear();
		param.put("companyId", getCompany().getId());
		List<CompanyExpressConfigEntity> freeAddressList = companyExpressConfigService.listCompanyExpressConfig(param);
		String normalDeliveryAddressIds = "";
		String expressDeliveryAddressIds = "";
		if (freeAddressList != null && freeAddressList.size() > 0) {
			for (CompanyExpressConfigEntity config : freeAddressList) {
				if (config.getExpressType() == 1) {
					normalDeliveryAddressIds = config.getAddressIdsStr();
				} else if (config.getExpressType() == 2) {
					normalDeliveryAddressIds = "all";
				} else if (config.getExpressType() == 3) {
					expressDeliveryAddressIds = config.getAddressIdsStr();
				} else if (config.getExpressType() == 4) {
					expressDeliveryAddressIds = "all";
				}
			}
		}
		request.setAttribute("normalDeliveryAddressIds", normalDeliveryAddressIds);
		request.setAttribute("expressDeliveryAddressIds", expressDeliveryAddressIds);
		
		//传递分享id
		request.setAttribute("shareId", request.getParameter("shareId"));
		return "wx/shoppingcart/checkout";
	}
	
	/**
	 * 转到购物车商品详情页面
	 * @param request
	 * @return String    
	 * @author xu_cc  
	 * @throws Exception exception
	 * @Date 创建时间：2018年1月13日 下午3:52:37
	 */
	@RequestMapping("/toShoppingCartProductPage")
	public String toShoppingCartProductPage(HttpServletRequest request) {
		try {
			// 查询目前购物车中的商品
			String userCode = getCurrentUserCodeWithAnonymous(request);
			// 用户勾选要结算的商品
			String shoppingcartIds = request.getParameter("shoppingIds");
			List<String> shoppingcartIdsList = new ArrayList<String>();
			if (StringUtil.isNotEmpty(shoppingcartIds)) {
				for (String id : shoppingcartIds.split(",")) {
					shoppingcartIdsList.add(id);
				}
			}
			// 查询待结算的商品
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("userCode", userCode);
			param.put("shoppingcartIds", shoppingcartIdsList);
			List<ShoppingCartEntity> cartList = shoppingCartService.listShoppingCart(param);
			if(cartList != null && cartList.size() > 0){
				for (ShoppingCartEntity product : cartList) {
					// 解析商品规格项
					if(StringUtil.isNotEmpty(product.getProductSpec())){
						List<ProductSpecEntity> productSpecList = JSONArray.parseArray(product.getProductSpec(), ProductSpecEntity.class);;
						product.setSpecList(productSpecList);
					}
				}
			}
			request.setAttribute("cartList", cartList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "wx/shoppingcart/shoppingcart_product";
	}
	
	/**
	 * 修改商品规格的数量
	 * @param request
	 * @return
	 */
	@RequestMapping("/editItemSpec")
	@ResponseBody
	public Map<String, Object> editItemSpec(ShoppingCartEntity  shoppingCartEntity, HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 商品规格
			String specList = request.getParameter("specListJson");
			List<ProductSpecEntity> productSpecList = null;
			if(!"[]".equals(specList)){
				productSpecList = JSONArray.parseArray(specList, ProductSpecEntity.class);
			}
			
			
			// 查询商品信息
			long productId = shoppingCartEntity.getProductId();
			ProductEntity product = productService.getProductById(productId);
			
			// 查询商品价格【为安全， 凡是涉及商品金额的，要后台重新计算，不采用前台传入的价格】
			BigDecimal productPrice = product.getBasePrice();
			List<ProductPriceEntity> priceList = productService.getProductPriceList(productId);
			// 客户级别
			String customerLevel = getCustomerLevel();
			if (priceList != null && priceList.size() > 0) {
				for (ProductPriceEntity price : priceList) {
					if (customerLevel.equals(price.getPriceLevel())) {
						productPrice = productPrice.add(price.getDiffPrice());
						break;
					}
				}
			}
			product.setBasePrice(productPrice);
			
			// 查询商品规格项的价格
			if(productSpecList != null && productSpecList.size() > 0){
				for (ProductSpecEntity productSpec : productSpecList) {
					// 查询规格价格
					ProductSpecEntity ppe = productSpecService.getProductSpecById(productSpec.getId());
					// 添加规格项的价格加到商品价格上
					productPrice = productPrice.add(ppe.getSpecPrice());
				}
			}
			
			// 购买数量
			String buyNum = request.getParameter("buyNum");
			shoppingCartEntity.setBuyNum(Integer.parseInt(buyNum));
			
			// 设置商品价格
			shoppingCartEntity.setProductPrice(productPrice);
			shoppingCartEntity.setProductBasePrice(product.getBasePrice());
			// 货主设置
			// TODO
			shoppingCartEntity.setProductOwnerCode(1);
			// 商品名称
			shoppingCartEntity.setProductName(product.getProductName());
			// 商品规格
			shoppingCartEntity.setProductSpec(specList);
			// 设置商品编码
			shoppingCartEntity.setProductCode(product.getProductCode());
			// 设置购物车中的用户名，未登录用户使用sessionId 后20位当作用户名
			String userCode = getCurrentUserCodeWithAnonymous(request);
			shoppingCartEntity.setModifier(userCode);
			// 添加购物车
			long id = shoppingCartService.updateShoppingCart(shoppingCartEntity);
			
			if(id != 0){
				resultMap.put(PublicStatus.RESULT_CODE, "1");
				resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
				resultMap.put("productPrice", shoppingCartEntity.getProductPrice());
			}else{
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			}
			return resultMap;
		} catch (Exception e) {
			handleException("往购物车中添加商品失败", logger, e);
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
		}
		return resultMap;
	}
	
	
	/**
	 * 查询购物车商品数量
	 * @param request
	 * @return
	 */
	@RequestMapping("/getShoppingcarCount")
	@ResponseBody
	public Map<String, Object> listCartItemCount( HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			if(isLogin(request)){
				String userCode = getUserCode();
				param.put("userCode", userCode);
				List<ShoppingCartEntity>  cartList = shoppingCartService.listShoppingCart(param);
				int count  = 0;
				if (null != cartList && cartList.size() > 0) {
					int total = 0;
					for (ShoppingCartEntity shopCar : cartList) {
						count += shopCar.getBuyNum();
					}
				}
				resultMap.put("count", count);
			}else{
				resultMap.put("count", 0);
			}
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
			return resultMap;
		} catch (Exception e) {
			handleException("查询购物车商品数量失败", logger, e);
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
		}
		return resultMap;
	}
	
}
